package Master;

import java.util.LinkedList;
import java.util.Queue;

/**
 * Created by IntelliJ IDEA.
 * User: lihengfeng
 * Date: 11-5-19
 * Time:
 * To change this template use File | Settings | File Templates.
 */
public class WorkerDispatcher extends Thread{

    private final Queue<TaskRunnable> queue;

/*    private int finishedJobs;*/
    private boolean isRunning = true;

    public WorkerDispatcher(){
        queue = new LinkedList<TaskRunnable>();
        /*finishedJobs = 0;*/
    }

   /* public void clearFinishedJobs(){
        finishedJobs = 0;
    }*/

    public void stopRunning(){
        this.isRunning = false;
    }

/*    public void increaseFinishedJobs(){
        this.finishedJobs++;
    }

    public int getFinishedJobs(){
        return finishedJobs;
    }*/

    public void add(TaskRunnable task){
        synchronized (queue){
            System.out.println(task.getEstimateTime());
            System.out.println("New task add " + ((Task)task).getTaskID());
            queue.offer(task);
            System.out.println("Queue Size " + queue.size());
            //resource.addTaskTime(task.getEstimateTime());
            queue.notify();
        }
    }


    public void run(){
        TaskRunnable task;
        while (true) {
            synchronized (queue) {

                while (queue.isEmpty()){
                    try {
                        queue.wait();
                    }
                    catch (InterruptedException ignored){

                    }
                }


                task = (TaskRunnable) queue.poll();
                System.out.println("!!!!!!!!!!!!Run Task " + ((Task)task).getTaskID());
                System.out.println("!!!!!!!!!!!!Queue Size " + queue.size());
            }

            try{
                if(task == null){
                    System.out.println("TASK NULL!!!!");
                }
                task.run();
            } catch (RuntimeException e) {
                System.out.println("Error happens while dispatcher is running..");
            }
        }
    }

}
    /*
    public void run(){
        TaskRunnable task=null;
            synchronized (queue) {
                while (!queue.isEmpty()){
                	 task = (TaskRunnable) queue.poll();
                	 task.run();
                }
            }
            System.out.println("here");
            }
    }
  
             
            try{
                if(task == null){
                    System.out.println("TASK NULL!!!!");
                }
                //task.run();
            } catch (RuntimeException e) {
                System.out.println("Error happens while dispatcher is running..");
            }
         }
    }
}*/